<template>
  <div class="my-img" v-loading="loading">
    <img :src="fileNew?.url" />
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, watch } from "vue";
import { previewEcmImage } from "../../utils/ecm";
import { previewImage } from "../../utils/download";

export default defineComponent({
  name: "previewImg",
  props: {
    type: {
      default: "ecm"
    },
    files: {
      type: Object,
      default: () => {}
    }
  },
  setup(props) {
    const loading = ref(false);
    let fileNew = ref(null);
    let index = 0;

    const getImageUrl = async file => {
      if (props.type === "ecm") {
        const res = await previewEcmImage(file.uuidFile, 80, 80);
        file["url"] = window.URL.createObjectURL(res);
      } else {
        const res = await previewImage(file);
        file["url"] = res;
      }
    };

    const getFile = async el => {
      let file;
      if (el.response) {
        await getImageUrl(el.response.data);
        file = { ...el.response.data };
      } else {
        await getImageUrl(el);
        file = { ...el };
      }
      return file;
    };

    watch(
      () => props.files,
      async el => {
        if (el.fileName && index === 0) {
          index++;
          loading.value = true;
          fileNew.value = await getFile(el);
          loading.value = false;
        }
      },
      {
        deep: true
      }
    );
    onMounted(async () => {
      if (props.files.fileName && index === 0) {
        index++;
        loading.value = true;
        fileNew.value = await getFile(props.files);
        loading.value = false;
      }
    });

    return {
      loading,
      fileNew
    };
  }
});
</script>
<style>
.my-img {
  width: 100%;
  height: 100%;
}
img {
  width: 100%;
  max-width: 100%;
  max-height: 100%;
}
</style>
